import { NextResponse, NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  console.log('Middleware triggered for:', request.nextUrl.pathname);
  
  // Get token from cookies
  const token = request.cookies.get('token')?.value
  console.log('Token found:', !!token);

  // Check if user is authenticated
  const isAuthenticated = !!token

  // If user is not authenticated, redirect to login
  if (!isAuthenticated) {
    console.log('Redirecting to /admin');
    return NextResponse.redirect(new URL('/admin', request.url))
  }

  // Allow authenticated users to proceed
  console.log('User authenticated, proceeding');
  return NextResponse.next()
}

export const config = {
  matcher: [
    '/admin/dashboard',
    '/admin/dashboard/:path*',
    '/admin/articles/:path*',
    '/admin/products/:path*',
    '/admin/users/:path*',
    '/admin/settings/:path*',
    // Add more protected routes here
  ]
}